//
//  ProductDetailsVC.m
//  sensen_ios
//
//  Created by pro on 16/2/23.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "ProductDetailsVC.h"

// 控制器
#import "ShopVC.h" // 商城首页
#import "ShopMessageVC.h" // 消息
#import "ShopCartVC.h" // 购物车

// 视图
#import "CarouselView.h" // 轮播视图
#import "ProductDetailView.h" // 商品详情视图
#import "ShopToolsView.h" // 下方工具栏
#import "ProductChoosePopView.h" // 商品规格选择弹出视图

// 单元格
#import "ProductDetailCell.h" // 商品详情介绍单元格
#import "ProductCell.h"
#import "CarouselCell.h"


// model
#import "ProductDetailModel.h" // 商品详情model

@interface ProductDetailsVC () <UITableViewDataSource, UITableViewDelegate, UIWebViewDelegate, ShopToolsViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource>
{
    
    NSArray *_carouselImgAry;
    
    NSMutableArray *_recommendItemsAry; // 商城推荐数组
    NSInteger _page;
    
    UIActivityIndicatorView *actView; // 菊花
}
// 数据
@property (nonatomic, strong) ProductDetailModel *model; // 商品详情
@property (nonatomic, assign) CGFloat detailRowHeight; // 商品详情单元格高度

@property (nonatomic, assign) BOOL isShowMore; // 是否右侧导航栏显示更多
@property (nonatomic, strong) UIView *moreView; // 点击导航栏右侧...的时候展示更多

@property (nonatomic, strong) ShopToolsView *toolsView; // 下方工具栏

// 视图
@property (nonatomic, strong) UITableView *tableView; // 表视图
@property (nonatomic, strong) ProductDetailView *productDeatilView; // 商品详情视图
@property (nonatomic, strong) UIWebView *webView; // 网页
@property (nonatomic, strong) UICollectionView *collectionView; // 商城推荐

@property (nonatomic, strong) ProductChoosePopView *popView; // 规格弹出视图
@end

@implementation ProductDetailsVC

#pragma mark - 视图方法
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self createLeftBackBarButtonItem:0.5];
    [self createRightBarButtonItems:0.5];
    
    // 创建视图
    [self _createViews];
    
    // 获取数据，并重排视图
    [self _getData];
    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    
    [self isNaviTranslucent:YES statesLightContent:YES];
    [self _setNaviAttributes:_tableView.contentOffset.y];

    // 隐藏标签栏
    MainTabBarController *main = (MainTabBarController *)self.tabBarController;
    [main hideTabBar];
    
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:YES];
    
    // 显示标签栏
    MainTabBarController *main = (MainTabBarController *)self.tabBarController;
    [main showTabBar];
    
    // 该控制器返回或者跳转的时候要删除更多视图
    _isShowMore = NO;
    [_moreView removeFromSuperview];
    _moreView = nil;
}
- (void)createLeftBackBarButtonItem:(CGFloat)bgAlpha {
    
    UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    customView.userInteractionEnabled = YES;
    // 设置半透明圆角背景
    customView.layer.cornerRadius = 15;
    
    customView.backgroundColor = [UIColor colorWithWhite:0.3 alpha:bgAlpha];
    
    // 设置点击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(leftClick:)];
    [customView addGestureRecognizer:tap];
    // 图标
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    imgView.userInteractionEnabled = YES;
    imgView.contentMode = UIViewContentModeScaleAspectFit;
    imgView.image = [UIImage imageNamed:@"导航栏_返回"];
    imgView.center = CGPointMake(customView.width / 2, customView.height / 2);
    [customView addSubview:imgView];
    
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithCustomView:customView];
    
    self.navigationItem.leftBarButtonItem = leftBarButton;
    
}
// 右侧按钮的样式可以自定义，由imgname控制，如果是文字则调用下面的接口
- (void)createRightBarButtonItems:(CGFloat)bgAlpha {
    
    NSArray *imgnameAry = @[@"下拉菜单按钮", @"商城首页_购物车"];
    NSMutableArray *itemsAry = [[NSMutableArray alloc] init];
    // 循环创建右侧按钮
    for (int i = 0; i < imgnameAry.count; i ++) {
        UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
        customView.userInteractionEnabled = YES;
        customView.tag = i + 1;
        // 设置半透明圆角背景
        customView.layer.cornerRadius = 15;
        
        customView.backgroundColor = [UIColor colorWithWhite:0.3 alpha:bgAlpha];
        
        // 设置点击手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(rightClick:)];
        [customView addGestureRecognizer:tap];
        // 图标
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
        imgView.userInteractionEnabled = YES;
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        imgView.image = [UIImage imageNamed:imgnameAry[i]];
        imgView.center = CGPointMake(customView.width / 2, customView.height / 2);
        [customView addSubview:imgView];
        
        UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:customView];
        [itemsAry addObject:rightBarButton];
        
    }
    self.navigationItem.rightBarButtonItems = itemsAry;
}
#pragma mark - 获取数据
- (void)_getData {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:_pid forKey:@"id"];
    if ([CommonCache getUserInfo] != nil) {
        [params setObject:[CommonCache getUserInfo].uid forKey:@"uid"];
    }
    
    [self _setViewStateWithLoading:YES];
    [SVProgressHUD showWithStatus:@"加载商品信息..."];
    [BoyeHttpClient post:@"BY_Product_detail" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
        
        [SVProgressHUD dismiss];
        
        [self _setViewStateWithLoading:NO];
        
        // 详情model
        _model = [[ProductDetailModel alloc] initContentWithDic:result];
        
        // 计算表视图第一个单元格的高度
        _detailRowHeight = ([_model.introduction getBoundingRectOfStringSize:CGSizeMake(SCREEN_WIDTH - 100, 10000) font:15].size.height + 10) + 10 + 10 + 20 + 10;
        
        // 设置规格属性
        _popView.detailModel = _model;
        _popView.skuAry = _model.skuAry;
        _popView.skuIdAry = _model.skuIdAry;
        _popView.skuNameAry = _model.skuNameAry;
        
        // 设置轮播图片
        _carouselImgAry = _model.imgs;
        
        // 设置是否收藏
        _toolsView.isCollected = [_model.favorite boolValue];
        _toolsView.pid = _model.p_id;
        [_tableView reloadData];
        
        // 设置webView
        NSString *urlStr = [NSString stringWithFormat:@"%@/Product/detail?id=%@", WEB_BASE_URL, _model.p_id];
        NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
        [_webView loadRequest:req];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"%@", error);
        [SVProgressHUD showErrorWithStatus:@"获取详情信息失败" withDuration:2];
        [self performSelector:@selector(leftAction:) withObject:nil afterDelay:2];
    }];
}

// 点击商城推荐时候加载推荐商品
- (void)_getRecommendProducts {
    
    _page = 1;
    NSDictionary *params = @{@"group_id":@"16",
                             @"page_size":@"1000",
                             @"page_no":@(_page)};
    
    [SVProgressHUD showWithStatus:@"请求推荐商品中..."];
    self.view.userInteractionEnabled = NO;
    [BoyeHttpClient post:@"BY_Product_queryByGroup" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
        
        if (_recommendItemsAry) {
            [_recommendItemsAry removeAllObjects];
        } else {
            _recommendItemsAry = [[NSMutableArray alloc] init];
        }
        
        if (![result[@"list"] isKindOfClass:[NSNull class]]) { // 有数据
            for (NSDictionary *dic in result[@"list"]) {
                ProductModel *model = [[ProductModel alloc] initContentWithDic:dic];
                [_recommendItemsAry addObject:model];
            }
        }
        [_collectionView reloadData]; // 刷新表视图
        
        [self performSelector:@selector(sss) withObject:nil afterDelay:0.001];
        
        [SVProgressHUD dismiss];
        self.view.userInteractionEnabled = YES;
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"加载失败" withDuration:2];
        self.view.userInteractionEnabled = YES;
    }];
}
- (void)sss {
    NSLog(@"推荐商品列表的高度:%lf", _collectionView.contentSize.height);
    _collectionView.height = _collectionView.contentSize.height;
    [_tableView reloadData];
}



#pragma mark - 创建视图
- (void)_createViews {
    
    // 创建底部的工具栏
    [self _createToolsView];
    [self _createPuoductDetailView]; // 创建商品详情视图
    [self _createWebView];
    [self _createCollectionView];
    [self _createTableView]; // 创建表视图
    
    [self _createPopView]; // 规格弹出视图
    [self _createTapToTopView];
    
}
// 下方工具栏
- (void)_createToolsView {
    
    _toolsView = [[ShopToolsView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 49)];
    _toolsView.delegate = self;
    _toolsView.bottom = SCREEN_HEIGHT;
    [self.view addSubview:_toolsView];
}
// 规格弹出视图
- (void)_createPopView {
    
    _popView = [[ProductChoosePopView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [self.view addSubview:_popView];
}


// 创建表视图
- (void)_createTableView {
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - _toolsView.height) style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    // 注册单元格
    [_tableView registerClass:[CarouselCell class] forCellReuseIdentifier:@"CarouselCell"];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"chooseCell"];
    [_tableView registerClass:[ProductDetailCell class] forCellReuseIdentifier:@"ProductDetailCell"];
    
}
// 创建商品详情视图
- (void)_createPuoductDetailView {
    
    _productDeatilView = [[ProductDetailView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 104)];
    
    // 回调block
    __weak typeof(self) weakSelf = self;
    _productDeatilView.chooseBlock = ^(NSInteger tag) {
        
        
        // 图文详情（网页）
        if (tag == 1) {
            
            weakSelf.webView.hidden = NO;
            weakSelf.collectionView.hidden = YES;
            weakSelf.webView.scrollView.contentOffset = CGPointZero;
            
            // 设置webView
            NSString *urlStr = [NSString stringWithFormat:@"%@/Product/detail?id=%@", WEB_BASE_URL, weakSelf.model.p_id];
            NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
            [weakSelf.webView loadRequest:req];
        }
        // 商城推荐
        else {
            weakSelf.collectionView.hidden = NO;
            weakSelf.webView.hidden = YES;
            weakSelf.collectionView.contentOffset = CGPointZero;
            // 获得数据
            [weakSelf _getRecommendProducts];
        }
        
    };
}
// 创建商品列表视图
- (void)_createCollectionView {
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 5;
    layout.minimumLineSpacing = 5;
    layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    CGFloat width = (SCREEN_WIDTH - 5 * 3) / 2.0;
    CGFloat height = width + 30 + 20 + 10;
    // 设置单元格尺寸
    layout.itemSize = CGSizeMake(width, height);
    
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1) collectionViewLayout:layout];
    // 设置代理和数据源方法
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    _collectionView.scrollEnabled = NO;
    
    // 注册单元格
    UINib *nib = [UINib nibWithNibName:@"ProductCell" bundle:nil];
    [_collectionView registerNib:nib forCellWithReuseIdentifier:@"ProductCell"];

}

// 创建网页视图
- (void)_createWebView {
    
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
    
    _webView.backgroundColor = [UIColor whiteColor];
    _webView.scrollView.showsHorizontalScrollIndicator = NO;
    _webView.scrollView.showsVerticalScrollIndicator = NO;
    _webView.scrollView.scrollEnabled = NO;
    _webView.scalesPageToFit = YES;
    _webView.delegate = self;
    
    UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    indicator.frame = CGRectMake(0, 0, _webView.width, _webView.height);
    indicator.backgroundColor = [UIColor whiteColor];
    indicator.hidesWhenStopped = YES;
    [_webView addSubview:indicator];
    indicator.center = CGPointMake(_webView.width / 2, _webView.height / 2);
    indicator.tag = 100;
    
    [indicator startAnimating];
    
}

#pragma mark - webView 代理事件
- (void)webViewDidStartLoad:(UIWebView *)webView {
    
    NSLog(@"webview开始加载");
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
    UIActivityIndicatorView *indicator = (UIActivityIndicatorView *)[webView viewWithTag:100];
    if ([indicator isAnimating]) {
        [indicator stopAnimating];
    }
    
    CGFloat height = [[webView stringByEvaluatingJavaScriptFromString: @"document.body.scrollHeight"] intValue];
    webView.height = height;
    NSLog(@"webView 高度:%lf", height);
    
    [_tableView reloadData];
    
}


#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}
// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        CarouselCell *carouselCell = [tableView dequeueReusableCellWithIdentifier:@"CarouselCell" forIndexPath:indexPath];
        
        carouselCell.carouselView.imgUrlstrAry = _carouselImgAry;
        
        return carouselCell;
    }
    if (indexPath.section == 1) {
        ProductDetailCell *productCell = [tableView dequeueReusableCellWithIdentifier:@"ProductDetailCell" forIndexPath:indexPath];
        
        // 设置属性
        productCell.model = _model;
        return productCell;
    }
    if (indexPath.section == 2) {
        
        UITableViewCell *chooseCell = [tableView dequeueReusableCellWithIdentifier:@"chooseCell"];
        chooseCell.textLabel.text = @"请选择规格分类";
        chooseCell.textLabel.textColor = [UIColor darkGrayColor];
        chooseCell.textLabel.font = FONT(14);
        chooseCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        chooseCell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return chooseCell;
    }
    if (indexPath.section == 3) {
        static NSString *identifier = @"webCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell){
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.backgroundColor = [UIColor whiteColor];
            
            [cell.contentView addSubview:_webView];
            [cell.contentView insertSubview:_collectionView atIndex:0];
            _collectionView.hidden = YES;

            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        return cell;
    }
    
    return nil;
}
// 设置单元格行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 第一组
    if (indexPath.section == 1) {
        
        if (_model != nil) {
            return _detailRowHeight;
        } else {
            return 80;
        }
    } else if (indexPath.section == 0) {
        return SCREEN_WIDTH;
    } else if (indexPath.section == 3) {
        return !_webView.hidden ? _webView.height : _collectionView.height;
    }
    else {
        return 44;
    }
}
// 设置组头高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    } else if (section == 3) {
        return 104;
    }
    return 5;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 3) {
        return _productDeatilView;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 2) {
        return 5;
    } else {
        return 0;
    }
}
// 单元格点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 2) {
        _popView.isOnlyConfirm = NO;
        [_popView show];
    }
}

#pragma mark - 滑动视图代理，UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat offset = scrollView.contentOffset.y;
    
    [self _setNaviAttributes:offset];
}


#pragma mark - collectionView 代理
// 定义展示的UICollectionViewCell的个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
// 定义展示的Section的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _recommendItemsAry.count;
}
// 每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ProductCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ProductCell" forIndexPath:indexPath];
    
    cell.model = _recommendItemsAry[indexPath.item];
    
    return cell;
}

// 单元格选中事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    // 跳转到详情页面
    ProductDetailsVC *vc = [[ProductDetailsVC alloc] init];
    ProductDetailModel *model = _recommendItemsAry[indexPath.row];
    vc.pid = model.p_id;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - 下方工具栏（立即购买，加入购物车）
- (void)shopToolsViewDidClick:(NSInteger)tag {
    
    _popView.isOnlyConfirm = YES; // 不显示立即购买和加入购物车
    
    switch (tag) {
        case 3:
        {
            UserModel *user = [CommonCache getUserInfo];
            if (user == nil) {
                LoginVC *vc = [[LoginVC alloc] init];
                BaseNavVC *naviVc = [[BaseNavVC alloc] initWithRootViewController:vc];
                [self presentViewController:naviVc animated:YES completion:nil];
            } else {
                _toolsView.isCollected = !_toolsView.isCollected;
                NSDictionary *params = @{@"product_id":_model.p_id,
                                         @"uid":user.uid,
                                         @"favorite_value":@(_toolsView.isCollected)
                                         };
                [BoyeHttpClient post:@"BY_Product_favorites" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
                    [SVProgressHUD showSuccessWithStatus:(_toolsView.isCollected ? @"添加收藏成功":@"取消收藏成功") withDuration:1.5];
                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    _toolsView.isCollected = !_toolsView.isCollected;
                    [SVProgressHUD showSuccessWithStatus:(!_toolsView.isCollected ? @"添加收藏失败":@"取消收藏失败") withDuration:1.5];
                }];
            }
            
        }
            break;
        case 4:
        {
            _popView.btnType = BtnTypeForAddToShopCar;
            [_popView show];
        }
            break;
        case 5:
        {
            _popView.btnType = BtnTypeForBuyNow;
            [_popView show];
        }
            break;
            
        default:
            break;
    }
}




#pragma mark - 点击事件
- (void)leftClick:(UITapGestureRecognizer *)tap {
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)rightClick:(UITapGestureRecognizer *)tap {
    // 下拉菜单
    if (tap.view.tag == 1) {
        
        if (_moreView == nil) {
            _moreView = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 100, 60, 100, 60)];
            _moreView.backgroundColor = [UIColor whiteColor];
            [_APP_KEYWINDOW addSubview:_moreView];
            _moreView.left = SCREEN_WIDTH;
            
            // 商城首页，消息
            NSArray *titles = @[@"商城首页",@"消息"];
            NSArray *imgNames = @[@"下拉菜单回到商城首页",@"下拉菜单消息"];
            for (int i = 0; i < titles.count; i ++) {
                // 总视图，用于点击
                UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, i * _moreView.height / 2.0, _moreView.width, _moreView.height / 2.0)];
                bgView.tag = i + 1;
                [_moreView addSubview:bgView];
                // 添加点击手势
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(naviRightTap:)];
                [bgView addGestureRecognizer:tap];
                // 图片
                UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 20, 20)];
                imgView.image = [UIImage imageNamed:imgNames[i]];
                [bgView addSubview:imgView];
                // 文字
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(imgView.right + 5, imgView.top, _moreView.width - imgView.width - 10, imgView.height)];
                label.userInteractionEnabled = YES;
                label.font = FONT(14);
                label.text = titles[i];
                label.textColor = [UIColor darkGrayColor];
                label.textAlignment = NSTextAlignmentLeft;
                [bgView addSubview:label];
            }
            
        }
        
        if (!_isShowMore) {
            [UIView animateWithDuration:0.3 animations:^{
                _moreView.left = SCREEN_WIDTH - _moreView.width;
            }];
        } else {
            [UIView animateWithDuration:0.3 animations:^{
                _moreView.left = SCREEN_WIDTH;
            }];
        }
        
        // 转换是否显示
        _isShowMore = !_isShowMore;
    }
    // 购物车
    else {
        
        ShopCartVC *vc = [[ShopCartVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

// 右侧导航栏按钮点击
- (void)naviRightTap:(UITapGestureRecognizer *)tap {
    if (tap.view.tag == 1) {
        // 点击商城首页
        for (UIViewController *vc in self.navigationController.viewControllers) {
            // 找到首页，并返回到首页
            if ([vc isKindOfClass:[ShopVC class]]) {
                [self.navigationController popToViewController:vc animated:YES];
                return;
            }
        }
    } else {
        // 点击消息
        ShopMessageVC *vc = [[ShopMessageVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}




#pragma mark - 其他方法（简化代码块）
#pragma mark -- 加载完成显示视图，加载中隐藏视图 --
- (void)_setViewStateWithLoading:(BOOL)isLoad {
    if (isLoad) {
        _tableView.hidden = YES;
        _toolsView.hidden = YES;
    } else {
        _tableView.hidden = NO;
        _toolsView.hidden = NO;
    }
}
#pragma mark -- 导航栏属性和视图变更 --
- (void)_setNaviAttributes:(CGFloat)offset {
    
    // top是我们想要位于导航栏（64）下方的位置
    CGFloat top = SCREEN_WIDTH;
    
    // offset是相对于屏幕的，所以要是top在导航栏正下方紧贴，则用offset和top-64 比较
    if (offset > 0) {
        UIColor *color;
        CGFloat alpha = offset / (top - 64);
        if (offset <= (top - 64)) {
            color = [UIColor colorWithRed:225/255.0 green:62/255.0 blue:10/255.0 alpha:alpha];
            [self createLeftBackBarButtonItem:(1 - alpha) * 0.5];
            [self createRightBarButtonItems:(1-alpha) * 0.5];
        } else {
            color = [UIColor colorWithRed:225/255.0 green:62/255.0 blue:10/255.0 alpha:0.99];
            [self createLeftBackBarButtonItem:0];
            [self createRightBarButtonItems:0];
            
        }
        // 根据滑动距离改变的透明度 改变导航栏背景颜色
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:color] forBarMetrics:UIBarMetricsDefault];
        
    } else {
        // 设置背景颜色为纯透明
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:[UIColor clearColor]] forBarMetrics:UIBarMetricsDefault];
        [self createLeftBackBarButtonItem:0.5];
        [self createRightBarButtonItems:0.5];
    }
}
// 创建放回顶部的按钮
- (void)_createTapToTopView {
    CGFloat x = SCREEN_WIDTH - 60;
    CGFloat y = SCREEN_HEIGHT - 64 - 49 ;
    UIView *tapToTopView = [[UIView alloc] initWithFrame:CGRectMake(x, y, 40, 40)];
    tapToTopView.backgroundColor = SS_NAVI_ORANGE_LIGHT_COLOR;
    tapToTopView.alpha = 0.5;
    tapToTopView.layer.cornerRadius = tapToTopView.width / 2;
    tapToTopView.clipsToBounds = YES;
    [self.view insertSubview:tapToTopView aboveSubview:_tableView];
    
    // 添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapToTop:)];
    [tapToTopView addGestureRecognizer:tap];
    
    // 添加图片
    x = (40 - 20) / 2.0;
    y  = 0;
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, 20, 20)];
    imgView.image = [UIImage imageNamed:@"商城首页_返回顶部"];
    [tapToTopView addSubview:imgView];
    // 添加文字
    x = 0;
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, tapToTopView.width, 12)];
    titleLabel.userInteractionEnabled = YES;
    titleLabel.font = FONT(8);
    titleLabel.text = @"顶部";
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [tapToTopView addSubview:titleLabel];
    
    // 设置位置
    imgView.top = (tapToTopView.height - imgView.height - titleLabel.height) / 2.0;
    titleLabel.top = imgView.bottom;
}


// 返回顶部
- (void)tapToTop:(UITapGestureRecognizer *)tap {
    
    // 滑动到顶部
    [_tableView setContentOffset:CGPointZero animated:YES];
}


#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
